from urllib.error import URLError
import feedparser
from download import Video, get_info_yt_video
# https://feedparser.readthedocs.io/en/latest/
from config import YT_CHANNEL_ID


class CheckFeed:
    def __init__(self):
        #self.url = f"https://www.youtube.com/feeds/videos.xml?channel_id={YT_CHANNEL_ID}"
        self.num_of_videos = 5
        self.url = f"https://vid.puffyan.us/feed/channel/{YT_CHANNEL_ID}"
        self.title = self._get_info()
        self.videos = []

    def read(self) -> list[Video]:
        self.videos = []
        try:
            feed = feedparser.parse(self.url)
            for entry in feed.entries[:self.num_of_videos]:
                video = get_info_yt_video(entry['link'])
                self.videos.append(video)
            return self.videos
        # TODO обработка ошибок
        except URLError:
            return []

    def _get_info(self):
        try:
            feed = feedparser.parse(self.url)
            return feed['channel']['title']
        except KeyError:
            raise Exception('You are provide not valid feed url. Check FEED_URL in config.py')
        except URLError:
            raise Exception('URL. Check FEED_URL in config.py')
